問題描述:
?
Given an integer?n, return the number of trailing zeroes in?n!.
?
Example 1:
?
Input: 3 Output: 0 Explanation:?3! = 6, no trailing zero.
?
Example 2:
?
Input: 5 Output: 1 Explanation:?5! = 120, one trailing zero.
?
Note:?Your solution should be in logarithmic time complexity.
?
思路:
在n!中,若想在結果的結尾產生0,只能是5乘以雙數、或者某個乘數結尾為0,如10,但10可視為5*2,20可以視為5*4.
綜上要想找n!中有幾個0,其實就是尋求在1到n這n個數中有幾個5.
其中25=5*5,這需要視為2個5
代碼目的就變成了尋找1到n這n個數中5的個數
代碼:
?
def trailingZeroes(self, n: int) -> int: if n <= 0: return 0 return sum( (n//(5**j)) for j in range(1, int(math.log(n, 5)) + 1))
?
n//(5**j) ,當j=1時,就是尋找在1到n這n個數中有幾個5
n//(5**j) ,當j=2時,就是尋找在1到n這n個數中有幾個25(5*5)(在上一步計算中,25會被統計,一次,但由于25是5*5,內部含有兩個5,因而在第二步需要再統計一次,即一共是算為2次)
依次類推
最后將結果累計相加,就可以計算出就是尋找在1到n這n個數中有幾個5了
?